package org.gongliang.controller.sys;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gongliang.common.base.BaseController;
import org.gongliang.common.base.Result;
import org.gongliang.entity.sys.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import springfox.documentation.annotations.ApiIgnore;

@Controller
@ApiIgnore
public class IndexController extends BaseController {

	/**
	 * 首页面
	 */
	@RequestMapping(value = "/")
	public String index() {
		return "index";
	}

	/**
	 * 获取用户所拥有的菜单
	 */
	@RequestMapping(value = "/getMenu")
	public @ResponseBody Result getMenu() {
		Result result = Result.success();
		
		result.setRows(getUser().getPermissions(Resources.RESOURCES_MENU));
		return result;
	}

	@Autowired
	private Producer captchaProducer;

	@RequestMapping(value = "/public/images/kaptcha")
	public ModelAndView initKaptcha(HttpServletRequest request, HttpServletResponse response) {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String capText = captchaProducer.createText();
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			ImageIO.write(bi, "jpg", out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
